<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
            style="float:right"
            type="primary"
            @click="handleSearchList"
            size="small">
          查询搜索
        </el-button>
        <el-button
            style="float:right;margin-right: 15px"
            @click="handleResetSearch"
            size="small">
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form :inline="true" :model="listQuery" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input v-model="listQuery.keyword" class="input-width" placeholder="角色名称" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd" style="margin-left: 20px">添加</el-button>
    </el-card>
    <div class="table-container">
      <el-table ref="roleTable" :data="list" style="width: 100%;" v-loading="listLoading" border>
        <el-table-column label="编号" width="100" align="center" prop="id" />
        <el-table-column label="角色名称" align="center" prop="name" />
        <el-table-column label="描述" align="center" prop="description" />
        <el-table-column label="用户数" width="100" align="center" prop="adminCount" />
        <el-table-column label="添加时间" width="160" align="center">
          <template #default="{ row }">{{ formatDate(row.createTime) }}</template>
        </el-table-column>
        <el-table-column label="是否启用" width="140" align="center">
          <template #default="{ row }">
            <el-switch
                @change="handleStatusChange($event, row)"
                :active-value="1"
                :inactive-value="0"
                v-model="row.status"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center">
          <template #default="{ row }">
            <el-row>
              <el-button size="mini" type="text" @click="handleSelectMenu(row)">分配菜单</el-button>
              <el-button size="mini" type="text" @click="handleSelectResource(row)">分配资源</el-button>
            </el-row>
            <el-row>
              <el-button size="mini" type="text" @click="handleUpdate(row)">编辑</el-button>
              <el-button size="mini" type="text" @click="handleDelete(row)">删除</el-button>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          v-model:current-page="listQuery.pageNum"
          v-model:page-size="listQuery.pageSize"
          :page-sizes="[5, 10, 15]"
          :total="total"
      />
    </div>
    <el-dialog :title="isEdit ? '编辑角色' : '添加角色'" v-model="dialogVisible" width="40%">
      <el-form :model="role" ref="roleForm" label-width="150px" size="small">
        <el-form-item label="角色名称：">
          <el-input v-model="role.name" style="width: 250px" />
        </el-form-item>
        <el-form-item label="描述：">
          <el-input v-model="role.description" type="textarea" :rows="5" style="width: 250px" />
        </el-form-item>
        <el-form-item label="是否启用：">
          <el-radio-group v-model="role.status">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm" size="small">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {useRouter} from 'vue-router';
import {fetchList, createRole, updateRole, updateStatus, deleteRole} from '@/api/role';
import {formatDate} from '@/utils/date';

const router = useRouter();

// 默认查询参数
const defaultListQuery = {
  pageNum: 1,
  pageSize: 5,
  keyword: null
};
const listQuery = reactive({...defaultListQuery});

// 默认角色对象
const defaultRole = {
  id: null,
  name: null,
  description: null,
  adminCount: 0,
  status: 1 // 默认启用
};

// 表格相关
const list = ref([]);
const total = ref(0);
const listLoading = ref(false);

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const role = reactive({...defaultRole});

// 获取角色列表
const getList = async () => {
  listLoading.value = true;
  try {
    const response = await fetchList(listQuery);
    list.value = response.data.data.list;
    total.value = response.data.data.total;
  } catch (error) {
    console.error('Failed to fetch role list:', error);
  } finally {
    listLoading.value = false;
  }
};

// 重置查询条件
const handleResetSearch = () => {
  Object.assign(listQuery, {...defaultListQuery});
  handleSearchList();
};

// 执行查询
const handleSearchList = () => {
  listQuery.pageNum = 1;
  getList();
};

// 分页大小改变时触发
const handleSizeChange = (val) => {
  listQuery.pageNum = 1;
  listQuery.pageSize = val;
  getList();
};

// 当前页码改变时触发
const handleCurrentChange = (val) => {
  listQuery.pageNum = val;
  getList();
};

// 添加角色
const handleAdd = () => {
  dialogVisible.value = true;
  isEdit.value = false;
  Object.assign(role, {...defaultRole});
};

// 修改状态
const handleStatusChange = async (status, row) => {
  try {
    await ElMessageBox.confirm('是否要修改该状态?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    await updateStatus(row.id, {status});
    ElMessage({
      type: 'success',
      message: '修改成功!'
    });
  } catch (error) {
    ElMessage({
      type: 'info',
      message: '取消修改'
    });
    // 回滚状态
    row.status = status === 1 ? 0 : 1;
  }
};

// 删除角色
const handleDelete = async (row) => {
  try {
    // 确认对话框
    await ElMessageBox.confirm('是否要删除该角色?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    console.log('Deleting role with ID:', row.id); // 调试日志

    // 构建请求参数
    const params = new URLSearchParams();
    params.append("ids", [row.id]); // 使用数组传递多个ID

    // 发送删除请求
    await deleteRole(params);

    // 显示成功消息
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });

    // 刷新角色列表
    await getList();
  } catch (error) {
    console.error('Error handling delete:', error);

    // 如果是用户取消了确认框，则不显示错误消息
    if (error.message !== 'cancel') {
      ElMessage({
        type: 'error',
        message: '删除失败，请重试!'
      });
    }
  }
};

// 编辑角色
const handleUpdate = (row) => {
  dialogVisible.value = true;
  isEdit.value = true;
  Object.assign(role, {...row});
};

// 确认对话框操作
const handleDialogConfirm = async () => {
  try {
    await ElMessageBox.confirm('是否要确认?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    if (isEdit.value) {
      await updateRole(role.id, role);
    } else {
      await createRole(role);
    }
    ElMessage({
      message: `${isEdit.value ? '修改' : '添加'}成功！`,
      type: 'success'
    });
    dialogVisible.value = false;
    await getList();
  } catch (error) {
    console.error(error);
  }
};

// 分配菜单
const handleSelectMenu = (row) => {
  router.push({path: '/employeeManagement/allocMenu', query: {roleId: row.id}});
};

// 分配资源
const handleSelectResource = (row) => {
  router.push({path: '/employeeManagement/allocResource', query: {roleId: row.id}});
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container, .operate-container {
  margin-bottom: 20px;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: right;
}

.input-width {
  width: 200px;
}

.btn-add {
  color: #fff;
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-footer {
  text-align: right;
}
</style>